"""
-----------------------------
   File Name:db_util
   Author:cwei
   date: 2023/7/27-15:36
-----------------------------
"""
import pymysql


class DBUtil:
    # 连接数据库
    @classmethod
    def __connect_db(cls):
        cls.conn = pymysql.connect(host='211.103.136.244', port=7068, user='student', password='KDTX_student_202304',
                                   database='huike')
        return cls.conn

    # 关闭数连接
    @classmethod
    def __close_db(cls):
        cls.conn.close()

    # 封装查询
    @classmethod
    def query_db(cls, sql):
        try:
            # 创建连接
            cls.conn = cls.__connect_db()
            # 获取数据
            cursor = cls.conn.cursor()
            cursor.execute(sql)
            # 提取数据
            res = cursor.fetchone()


        except Exception as e:
            print(e)

        finally:
            # 关闭游标
            cursor.close()

            # 关闭连接
            cls.conn.close()
            return res

    # 封装 增删改
    @classmethod
    def update_db(cls, sql):
        try:
            # 创建连接
            cls.conn = cls.__connect_db()
            # 获取数据
            cursor = cls.conn.cursor()
            cursor.execute(sql)
            rows = cls.conn.affected_rows()
            print("影响数据的行数:", rows)
            cls.conn.commit()

        except Exception as e:
            print(e)
            cls.conn.rollback()

        finally:
            # 关闭游标
            cursor.close()

            # 关闭连接
            cls.conn.close()

            return rows


if __name__ == '__main__':
    # print(DBUtil.query_db('select * from t_book;'))
    # DBUtil.update_db("INSERT  INTO t_book (id,title,pub_date)values(0,'四国志','2022-01-09')")
    # DBUtil.update_db("UPDATE t_book SET title = '三英战吕布吧' WHERE  id =1902471043")

    # DBUtil.update_db(
    #     "INSERT  INTO t_book (id,title,pub_date,`read`)values(1314,'《Python从入门到放弃》','2020-01-01',50)")
    # DBUtil.update_db("UPDATE t_book SET COMMENT = 250 WHERE  id =1314")
    # # DBUtil.update_db("DELETE FROM t_book WHERE id=1314")
    # DBUtil.update_db("UPDATE t_book SET is_delete = 1 WHERE  id =1314")
    # print(DBUtil.query_db("select is_delete from t_book where id = 1314"))

    print(DBUtil.query_db("select mobile from bs_user where id =1063705989926227968")[0])
